package com.jzlin.funhub.admin.service.chatai.support;

import cn.hutool.core.util.IdUtil;
import com.jzlin.funhub.admin.service.chatai.model.constant.BizConstant;
import com.jzlin.funhub.admin.service.chatai.model.enums.ChatAiMessageRole;
import com.jzlin.funhub.admin.service.chatai.store.ChatAiMessageRecord;
import com.jzlin.funhub.admin.service.chatai.store.IChatStore;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * AI问答服务抽象模板类.
 *
 * @author linjz
 * @since 2024/11/12
 */
public abstract class AbstractChatAiService implements IChatAiService {

    @Autowired
    private IChatStore chatStore;

    /**
     * 处理消息
     *
     * @param message 消息
     */
    @Override
    public void handleMessage(BaseChatMessage message) {
        storeUserChatMessage(message);
        //if (Optional.ofNullable(message.getConfig()).map(Map::g).orElse(false)) {
            handleBySse(message);
        //}
    }

    private void storeUserChatMessage(BaseChatMessage message) {
        Long now = System.currentTimeMillis();
        ChatAiMessageRecord record = ChatAiMessageRecord.builder()
                .role(ChatAiMessageRole.USER.getValue())
                .content(message.getMessage())
                .sessionId(message.getSessionId())
                .startTime(now)
                .endTime(now)
                .build();
        chatStore.saveMessage(record);
    }

    public void storeChatMessage(String sessionId, String content, ChatAiMessageRole role, Long startTime, Long endTime) {
        ChatAiMessageRecord record = ChatAiMessageRecord.builder()
                .role(role.getValue())
                .content(content)
                .sessionId(sessionId)
                .startTime(startTime)
                .endTime(endTime)
                .build();
        chatStore.saveMessage(record);
    }

    /**
     * 流式通信
     *
     * @param message 消息
     */
    protected abstract void handleBySse(BaseChatMessage message);

    /**
     * 创建会话id
     */
    @Override
    public String createSessionId() {
        return IdUtil.getSnowflake().nextIdStr();
    }

    /**
     * 获取会话上下文
     * @param sessionId 会话id
     * @return
     */
    protected ChatRefContext getChatRefContext(String sessionId) {
        ChatRefContext chatRefContext = new ChatRefContext();

        List<ChatAiMessageRecord> historyMessage = chatStore.getRefContextMessage(sessionId, BizConstant.CHAT_AI_REF_CONTEXT_COUNT_DEFAULT);
        chatRefContext.setHistoryMessage(historyMessage);

        return chatRefContext;
    }

    /**
     * 对消息内容进行传输前转换
     * @param content 消息内容
     * @return
     */
    protected String transferSseContent(String content) {
        String result;
        // sse传输时开头的空格会被忽略，因此使用占位符代替，接收者手动替换为空格
        if (content.startsWith(" ")) {
            result = content.replaceFirst(" ", "{{SPACE}}");
        } else {
            result = content;
        }
        // 换行符
        return result.replace("\n", "\\\\n");
    }
}
